<style>
    .table-select-wrapper {
        width: 100%;
        overflow: auto;
    }
    
    .table-wrapper {
        height: 410px;
        width: 100%;
        overflow: hidden;
        margin-bottom: 20px;
        border-bottom: 1px solid #D1D5DE;
        position: relative;
    }
    
    .table-thead {
        position: absolute;
        top: 0;
        right: 0;
        left: 0;
        bottom: 10px;
        overflow: auto;
        z-index: 1;
        text-align: center;
    }
    
    .table-tbody {
        position: absolute;
        top: 35px;
        left: 0;
        bottom: 10px;
        width: 100%;
        overflow: auto;
        text-align: center;
        z-index: 1;
    }
    
    .table-tbody tr {
        cursor: pointer;
    }
    
    .table-tbody tr:hover {
        background-color: #f1f1f1
    }
    
    .table-thead th,
    .table-thead td,
    .table-tbody th,
    .table-tbody td {
        border: 1px solid #ddd;
    }
    
    .active {
        background-color: #f1f1f1
    }
    
    .table-thead th>p,
    .table-tbody td>p {
        width: 150px;
        height: 35px;
        line-height: 35px;
        text-align: center;
        margin: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    #WtGoodpage {
        text-align: right;
        padding-right: 10px;
    }
    
    #wtGoodsQuery .pageCount {
        height: 34px;
        line-height: 34px;
        width: 100%;
        background-color: #F0F0F0;
        font-size: 14px;
        padding-left: 10px;
    }
</style>

<div id="wtGoodsQuery" class="goodsSelectDialogContent" style="width: 100%!important;">
    <form class="form-inline search" role="search">
        <div class="form-group">
            <label for="searchInputForGoods">代码/拼音码/名称/规格：</label>
            <input type="text" id="searchText" class="form-control" placeholder="Search">
            <!-- <div class="radio" id="liutong">
          	<label>
          		<input value="0" type="radio" name="type" checked>
          	</label>流通
        	</div>
        	<div class="radio" id="buliutong">
          		<label><input value="1"
                                  type="radio"
                                  name="type"></label>不流通
        </div> -->
        </div>
        <div class="btn-group">
            <button type="button" id="sureBtn" class="btn btn-primary">确定</button>
            <button type="button" id="cancelBtn" class="btn btn-primary">取消</button>
        </div>

    </form>
    <div class="table-wrapper">
        <div id='pTableFix' class="table-thead">
            <table>
                <thead class="thead">
                    <tr>
                        <th>
                            <p>物品代码</p>
                        </th>
                        <th>
                            <p>物品名称</p>
                        </th>
                        <th>
                            <p>供应商</p>
                        </th>
                        <th>
                            <p>规格型号</p>
                        </th>
                        <th>
                            <p>计量单位</p>
                        </th>
                        <th>
                            <p>最新税后单价</p>
                        </th>
                        <!--<th> <p>最新税前单价</p></th> 
				    	<th><p>供货单位</p></th>-->
                    </tr>
                </thead>
            </table>
        </div>
        <div id='pTable' class="table-tbody">
            <table class="tbody">
            </table>
        </div>
    </div>
    <div id="WtGoodpage"></div>
    <div id="WtBatch"></div>
    <div class="pageCount">查询结果：<span>0</span>条</div>
</div>
<script src="js/common/laypage/laypage.js"></script>
<script>
    var goodsDatas = []; //物品数组
    var goodsBatch = {}; //库存
    var pageCount = 0; //数量
    var nowPage = 1; //当前页
    var pageSize = 20;
    var pages = 0; // 页数
    var selectIndex = 0;
    var pTableFix = document.getElementById('pTableFix');
    var pTable = document.getElementById('pTable');
    $('#goodsSelectWrap').show();
    layer.open({
        type: 1,
        area: '910px',
        title: '物品查询',
        content: $('#wtGoodsQuery'),
        cancel: function() {
            $('.layui-layer-shade').remove();
            $('#goodsSelectWrap').hide();
            $('#goodsSelectWrap').empty();
        }
    });
    initData();
    $('#searchText').on('keyup', function() {
        debounce(initData(), 500);

    })
    $('#sureBtn').on('click', function() {
        window.frames[0].postMessage(goodsDatas[selectIndex], $('#main>iframe').attr('src')); //向子页面发送数据
        $('.layui-layer-shade').remove();
        $('#goodsSelectWrap').hide();
        $('#goodsSelectWrap').empty();
    })
    $('#cancelBtn').on('click', function() {
        $('.layui-layer-shade').remove();
        $('#goodsSelectWrap').hide();
        $('#goodsSelectWrap').empty();
    })
    $('#wtGoodsQuery table').on('click', 'tr', function() {
        selectIndex = $(this).index();
        getBatchStatus(goodsDatas[selectIndex]).then(function(data) {
            goodsBatch = Object.assign({}, data, {
                "GoodsName": goodsDatas[selectIndex].GoodsName ? goodsDatas[selectIndex].GoodsName : ""
            })
            randerBatchHtml(goodsBatch)
        })
        $(this).addClass('active').siblings().removeClass('active')
    })
    $('#wtGoodsQuery table').on('dblclick', 'tr', function() {
            selectIndex = $(this).index();
            getBatchStatus(goodsDatas[selectIndex]).then(function(data) {
                goodsBatch = Object.assign({}, data, {
                    "GoodsName": goodsDatas[selectIndex].GoodsName ? goodsDatas[selectIndex].GoodsName : ""
                })
                randerBatchHtml(goodsBatch)
            })
            window.frames[0].postMessage(goodsDatas[selectIndex], $('#main>iframe').attr('src')); //向子页面发送数据
            $('.layui-layer-shade').remove();
            $('#goodsSelectWrap').hide();
            $('#goodsSelectWrap').empty();
        })
        //设置div为滚动条的宽度，盖住pTableFix滚动条
    function setdivWidth() {
        var scrollbarWidth = pTable.offsetWidth - pTable.clientWidth;
        if (scrollbarWidth > 5) {
            $('.table-wrapper').append('<div style="position:absolute;top:0;right: 0;z-index:5;background:#f1f1f1;width: ' + scrollbarWidth + 'px;height:35px;"></div>')
            $("#pTableFix").css('right', scrollbarWidth + 'px')
        }
    }

    function scrollBar() {
        pTable.onscroll = function() {
            var pTableLeft = this.scrollLeft;
            pTableFix.scrollLeft = pTableLeft;
        }

    }
    //分页初始化
    function initData() {
        getGoodsDatas(nowPage, pageSize).then(function(res) {
            goodsDatas = res.pageContent;
            pageCount = res.pageCount;
            pages = Math.ceil(res.pageCount / res.pageSize)
            selectIndex = 0;
            setTableHtml(goodsDatas)
            $('.pageCount span').html(pageCount);
            $('#WtBatch').empty();

            getBatchStatus(goodsDatas[selectIndex]).then(function(data) {
                goodsBatch = Object.assign({}, data, {
                    "GoodsName": goodsDatas[selectIndex].GoodsName ? goodsDatas[selectIndex].GoodsName : ""
                })
                randerBatchHtml(goodsBatch)
            })
            setdivWidth();
            scrollBar();
            layPage({
                cont: document.querySelector('#WtGoodpage'),
                curr: nowPage,
                pages: pages,
                jump: function(obj, first) {
                    if (!first) {
                        //得到了当前页，用于向服务端请求对应数据
                        nowPage = obj.curr;
                        getGoodsDatas(nowPage, pageSize).then(function(res) {
                            selectIndex = 0;
                            goodsDatas = res.pageContent;
                            $('#WtBatch').empty();
                            setTableHtml(goodsDatas)
                            getBatchStatus(goodsDatas[selectIndex]).then(function(data) {
                                goodsBatch = Object.assign({}, data, {
                                    "GoodsName": goodsDatas[selectIndex].GoodsName ? goodsDatas[selectIndex].GoodsName : ""
                                })
                                randerBatchHtml(goodsBatch)
                            })
                        })
                    }
                }
            });

        })


    }
    //库存
    function randerBatchHtml(data) {
        $('#WtBatch').empty();
        var html = ""
        html += "<p style='padding: 5px;font-size: 14px;color: #333;'><span style='font-weight: bold;'>物品名词：</span>" + data.GoodsName + "&nbsp;<span style='font-weight: bold;'>库存数：" + data.GoodsCount + "</span>&nbsp;<span style='font-weight: bold;'>最新进货时间：" + data.LatestReceiveTime + "</span></p>"
        $('#WtBatch').html(html)
    }
    //初始化表格
    function setTableHtml(data) {
        var html = ""
            //  res.pageContent
            
        data.forEach(function(item) {
            html += "<tr>";
            html += "<td><p>" + item.GoodsCode + "</p></td>";
            html += "<td><p>" + item.GoodsName + "</p></td>";
            html += '<td><p>' + item.SupplierName+ '</p></td>';
            html += "<td><p>" + item.GoodsSpec + "</p></td>";
            html += "<td><p>" + item.BoxUnit + "</p></td>";
            html += "<td><p>" + item.LatestPrice + "</p></td>";
            //if (typeof item.TaxRate === 'number') {
            //     if (item.TaxRate === 0) {
            //    	item.PreTaxPrice = item.LatestPrice
            //    } else {
            //    	item.PreTaxPrice = (parseFloat(item.LatestPrice) / (1 + item.TaxRate)).toFixed(3)
            //    }
            //  }

            // html+="<td><p>"+item.PreTaxPrice+"</p></td>";
            // html+="<td><p>"+item.SupplierName+"</p></td>";
            html += "</tr>"
        })

        $('#pTable .tbody').html(html)
        $('#pTable .tbody tr').eq(selectIndex).addClass('active').siblings().removeClass('active')
    }

    function conditionModel(ColumnName, FullString, Oper, Value, Type) {

        var obj = {
            "ColumnName": ColumnName,
            "FullString": FullString,
            "Oper": Oper,
            "Value": Value,
            "Type": Type
        }
        return obj;
    }

    function conditionsModel(Conditions, Type) {
        var obj = {
            "Conditions": Conditions,
            "Type": Type
        }
        return obj
    }
    //库存查询
    function getBatchStatus(obj) {
        if (!obj || obj == undefined) {
            return new Promise(function(resolve, reject) {
                var data = {
                    "GoodsID": "",
                    "GoodsCount": 0.0,
                    "LatestReceiveTime": ""
                }
                resolve(data)
            })
        }
        var goodsID = obj.GoodsID;
        var deptInfo = JSON.parse(localStorage.getItem("deptInfo"))
        var parms = {
            className: 'StoreBatchManager',
            method: 'GetGoodsBatchStatus',
            goodsID: goodsID,
            deptAccountID: deptInfo.DeptAccountID,
        }
        return _fetch(parms)
    }
    //物品查询
    function getGoodsDatas(nowPage, pageSize) {
        var condition;
        var deptInfo = JSON.parse(localStorage.getItem("deptInfo"))
            //var IsOpen = $(".radio input[type='radio']:checked").val()==0?true:false
            //var Valid = conditionModel("wp.IsValid", null, "Equal", true, "Boolean")
            //var Open = conditionModel("wp.IsOpen", null, "Equal", IsOpen, "Boolean")
            // var ImmediatelyUse = conditionModel("wp.IsImmediatelyUse", null, "Equal", true, "Boolean")
            // var GoodsBookID = conditionModel("wp.GoodsBookID", null, "Equal", window.Param.Openparm.GoodsBook, "String")
        var Ksdm = conditionModel("DeptID", null, "Equal", deptInfo.Ksdm, "String")
        if ($('#searchText').val() !== '' && $('#searchText').val() !== undefined && $('#searchText').val() !== null) {
            var st = $('#searchText').val()
            var PyCode = conditionModel("b.PyCode", null, "Like", "%" + st + "%", "String")
            var GoodsCode = conditionModel("b.GoodsCode", null, "Like", "%" + st + "%", "String")
            var GoodsName = conditionModel("b.GoodsName", null, "Like", "%" + st + "%", "String")
            var GoodsSpec = conditionModel("b.GoodsSpec", null, "Like", "%" + st + "%", "String")
            var arr = [PyCode, GoodsCode, GoodsName, GoodsSpec]
            var condition1 = conditionsModel(arr, "OR")
            var arr1 = [Ksdm, condition1]
            condition = conditionsModel(arr1, "AND")
        } else {
            //var arr1 = [Valid, Open, ImmediatelyUse, GoodsBookID] 	
            //condition = conditionsModel(arr1, "AND")
            condition = Ksdm
        }
        var parms = {
            className: 'Dept2GoodsForYgptManager',
            method: 'GetGoodsForWeb',
            condition: JSON.stringify(condition),
            nowPage: nowPage,
            pageSize: pageSize
        }
        return _fetch(parms);

    }

    function _fetch(parms) {
        return new Promise(function(resolve, reject) {
            $.ajax({
                type: 'POST',
                url: getRootPath() + '/api/sendPostRequest',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                data: JSON.stringify(parms),
                success: function(res) {
                    if (res.issuccess == 0) {
                        var result = res.result.match(/^[ ]*$/) ? res.result : JSON.parse(res.result);
                        resolve(result)
                    } else {
                        reject(res.Message);
                    }
                },
                error: function(err) {
                    new Error(err)
                }
            });
        });
    }

    function debounce(handler, delay) {
        var timer;

        return function() {
            var self = this,
                arg = arguments;

            clearTimeout(timer);

            timer = setTimeout(function() {
                handler.apply(self, arg)
            }, delay)
        }
    }

    function getRootPath() {
        //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
        var curWwwPath = window.document.location.href;
        //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
        var pathName = window.document.location.pathname;
        var pos = curWwwPath.indexOf(pathName);
        //获取主机地址，如： http://localhost:8083
        var localhostPaht = curWwwPath.substring(0, pos);
        //获取带"/"的项目名，如：/uimcardprj
        var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
        return (localhostPaht + projectName + '/');
    };
</script>